<?php

/*
 CI Library User
 Written by: Ciprian Dimofte - 01-17-2010
 */

class User{
    public $CI;
    public $user_id = FALSE;
    public $user_account = array();
    public $user_profile = array();
    public $user_limits  = array();
    
    public function __construct(){
        $this->CI =& get_instance();
        if(!$this->user_id){
            $this->user_id = $this->CI->session->userdata("uid_logged_in");
        }
        if(!$this->user_id){
            $this->user_id = "0";
        }
        $this->query_all_user_data();
    }
    
    public function query_all_user_data(){
        //This user is not guest
        if($this->user_id != 0){
            
            $account_type_query = $this->CI->db->query("
                                                    SELECT 
                                                        u.last_login_ip,
                                                        u.user_email,
                                                        u.user_password,
                                                        u.user_ballance,
                                                        u.user_account_status,
                                                        u.user_full_name,
                                                        u.user_city,
                                                        u.user_state,
                                                        u.user_zip,
                                                        u.user_country,
                                                        u.user_registration_country,
                                                        u.user_registration_ip,
                                                        u.user_ref_by,
                                                        u.user_expiration_date,
                                                        l.ID,
                                                        l.account_name,
                                                        l.download_speed,
                                                        l.max_download_file_size,
                                                        l.max_upload_file_size,
                                                        l.no_downloads_files_lifetime,
                                                        l.remote_uploads,
                                                        l.advertising_present,
                                                        l.upload_queue_size,
                                                        l.simultaneous_uploads_number
                                                    FROM 
                                                        users AS u 
                                                    LEFT JOIN 
                                                        account_types as l 
                                                    ON u.user_account_type_id = l.ID 
                                                    WHERE u.ID = " . $this->CI->db->escape($this->user_id) . " LIMIT 1");
        }else{
            //This user is Guest
            $account_type_query = $this->CI->db->query("
                                                    SELECT 
                                                        l.ID,
                                                        l.account_name,
                                                        l.download_speed,
                                                        l.max_download_file_size,
                                                        l.max_upload_file_size,
                                                        l.no_downloads_files_lifetime,
                                                        l.remote_uploads,
                                                        l.advertising_present,
                                                        l.upload_queue_size,
                                                        l.simultaneous_uploads_number
                                                    FROM 
                                                        account_types AS l 
                                                    WHERE l.ID = '0' 
                                                    LIMIT 1
                                                   ");
        }
        $user_account = $account_type_query->row();
        if($this->user_id != 0){
	        //Define the user_account first
	        $this->user_account['user_email'] = $user_account->user_email;
	        $this->user_account['user_password'] = $user_account->user_password;
	        $this->user_account['user_account_status'] = $user_account->user_account_status;
	        $this->user_account['user_ballance'] = $user_account->user_ballance;
	        $this->user_account['user_expiration_date'] = $user_account->user_expiration_date;
	        $this->user_account['last_login_ip'] = $user_account->last_login_ip;
	        $this->user_account['user_ref_by'] = $user_account->user_ref_by;
	        
	        
	        //Now define the user_profile
	        $this->user_profile['user_full_name'] = $user_account->user_full_name;
	        $this->user_profile['user_city'] = $user_account->user_city;
	        $this->user_profile['user_state'] = $user_account->user_state;
	        $this->user_profile['user_zip'] = $user_account->user_zip;
	        $this->user_profile['user_country'] = $user_account->user_country;
	        $this->user_profile['user_registration_country'] = $user_account->user_registration_country;
	        $this->user_profile['user_registration_ip'] = $user_account->user_registration_ip;
        }
        //Now define the user limits
        $this->user_limits['account_type_id'] = $user_account->ID;
        $this->user_limits['account_name'] = $user_account->account_name;
        $this->user_limits['download_speed'] = $user_account->download_speed;
        $this->user_limits['max_download_file_size'] = $user_account->max_download_file_size;
        $this->user_limits['max_upload_file_size'] = $user_account->max_upload_file_size;
        $this->user_limits['no_downloads_files_lifetime'] = $user_account->no_downloads_files_lifetime;
        $this->user_limits['remote_uploads'] = $user_account->remote_uploads;
        $this->user_limits['advertising_present'] = $user_account->advertising_present;
        $this->user_limits['upload_queue_size'] = $user_account->upload_queue_size;
        $this->user_limits['simultaneous_uploads_number'] = $user_account->simultaneous_uploads_number;
        
    }
    
    public function is_upgradable_to_what(){
    	$current_cost_query = "
    	         SELECT app.rate_cost 
    	         FROM account_payment_plans AS app 
    	         LEFT JOIN account_types AS at 
    	            ON at.ID = app.account_type_id
    	         WHERE 
    	            at.ID = ? 
    	               AND
    	            app.rate_time = ?
    	         ";
    	$sel_current = $this->CI->db->query($current_cost_query, array($this->user_limits['account_type_id'], "7"));
    	$res_current = $sel_current->row();
    	$current_cost = $res_current->rate_cost;
    	
    	if(!$current_cost){
    		$current_cost = 0;
    	}
    	
    	if($current_cost == -1){
    		$current_cost = 999999;
    	}
    	
    	$greater_cost_query = "
    	                      SELECT at.account_name 
    	                      FROM account_payment_plans AS app 
    	                      LEFT JOIN account_types AS at 
    	                          ON at.ID = app.account_type_id 
    	                      WHERE 
    	                          app.rate_cost > ?
    	                              AND
    	                          app.rate_time = ?
    	                      ";
        $sel_greater = $this->CI->db->query($greater_cost_query, array($current_cost, "7"));
        $res_greater = $sel_greater->result();
        
        
        return $res_greater;
    }
    
    public function get_user_files($no_only = FALSE){
    	
    	if($this->CI->session->userdata("uid_logged_in") > 0){
	    	$query_files  = "SELECT ";
	    	if($no_only == TRUE){
	    	   $query_files .= "COUNT(f.ID) AS total_number ";
	    	}else{
	    	   $query_files .= "f.file_name, f.file_size, f.file_type, f.file_code, f.file_description, f.file_date, f.server_id, f.file_password ";
	    	}
	    	$query_files .= "FROM files AS f ";
	    	$query_files .= "LEFT JOIN users AS u ";
	    	$query_files .= "ON f.user_id = u.ID ";
	    	$query_files .= "WHERE u.ID = ?";
    	
	    	$sel_files = $this->CI->db->query($query_files, array($this->user_id));
	    	if($no_only == TRUE){
	    		$res_files = $sel_files->row();
	    	}else{
	    		$res_files = $sel_files->result();
	    	}
	    	return $res_files;
    	}else{
    		return FALSE;
    	}
    }
    
    
    public function do_auth(){
    	
    	$email = $this->CI->input->post("email_address");
    	$password = $this->CI->input->post("account_password");
    	if(!$email){
    	   $email = $this->CI->input->post("email");
    	}
        if(!$password){
        	$password = $this->CI->input->post("password");
        }
        
        $now = time();
        
        $sel_user = $this->CI->db->query("SELECT ID,user_expiration_date FROM users WHERE user_email = ? AND user_password = ? AND user_account_status = ?", array($email, md5($password), '1'));
        $res_user = $sel_user->row();
        
        if($res_user->ID){

            //Expire the user account if his account expired.
        	if($res_user->user_expiration_date <= $now && $res_user->user_expiration_date != "-1"){
        		$this->CI->db->query("
        		UPDATE users SET
        		user_expiration_date = ?,
        		user_account_type_id = ?
        		WHERE ID = ?
        		", array('-1', '1', $res_user->ID));
        	}
            
        	//Update login_ip
        	$this->CI->db->query("
                UPDATE users SET
                last_login_ip = ?
                WHERE ID = ?
                ", array($this->CI->input->ip_address(), $res_user->ID));
        	
        	$this->CI->session->set_userdata("uid_logged_in", $res_user->ID);
        	$this->user_id = $res_user->ID;
            $this->query_all_user_data();
            
        }else{
        	return FALSE;
        } 
    }
    
    public function logout(){
    	$this->CI->session->unset_userdata("uid_logged_in");
    	$this->CI->session->unset_userdata("ref_by");
    	$this->CI->session->unset_userdata("last_amount");
        $this->CI->session->unset_userdata("account_type_id");
    }
    
    public function do_signup(){
    	//Validate form first
    	$err = array();
    	$email = $this->CI->input->post("email_address");
    	$password = $this->CI->input->post("account_password");
    	$password_confirm = $this->CI->input->post("account_password_confirm");
    	$his_ip = $this->CI->input->ip_address();
    	
    	$full_name = $this->CI->input->post("full_name");
    	$city = $this->CI->input->post("city");
    	$state = $this->CI->input->post("state");
    	$zip = $this->CI->input->post("zip");
    	$country = $this->CI->input->post("country");
    	$plan_id = $this->CI->input->post("plan_id");
    	
    	
    	//Check if email already exists
        $sel_ex_user = $this->CI->db->query("
        SELECT ID FROM users
        WHERE user_email = ?
        ", array($email));
        $res_ex_user = $sel_ex_user->row();
        
    	if($res_ex_user->ID){
    		$err[] = "This email address is already used by another user";
    	}
    	
        if(!$plan_id){
            $err[] = "You must select an account type";
        }
    	
    	if(!$email){
    		$err[] = "Email is required";
    	}
        if(!$password){
            $err[] = "Password is required";
        }
        if($password != $password_confirm){
            $err[] = "Password doesn't match confirmation";
        }
    	
    	if(count($err) == 0){
    		//Check referal validity
    		$valid_ref_id = $this->CI->utility->validate_ref();
    		if($valid_ref_id == TRUE){
    			$u_ref_by = $this->CI->session->userdata("ref_by");
    		}else{
    			$u_ref_by = 0;
    		}
    		$real_country = $this->CI->ip2country->get_country($his_ip);
    		$this->CI->db->query("
    		INSERT INTO users
    		(
    		user_ref_by,
    		user_email,
    		user_password,
    		user_account_type_id,
    		user_ballance,
    		user_account_status,
    		user_full_name,
    		user_city,
    		user_state,
    		user_zip,
    		user_country,
    		user_registration_country,
    		user_registration_ip,
    		user_expiration_date
    		)
    		VALUES
    		(
    		'".$u_ref_by."',
    		".$this->CI->db->escape($email).",
    		".$this->CI->db->escape(md5($password)).",
    		'1',
    		'0',
    		'1',
    		".$this->CI->db->escape($full_name).",
    		".$this->CI->db->escape($city).",
    		".$this->CI->db->escape($state).",
    		".$this->CI->db->escape($zip).",
    		".$this->CI->db->escape($country).",
    		".$this->CI->db->escape($real_country['COUNTRY']).",
    		'".$his_ip."',
    		'-1'
    		)
    		");

            //Remove extra useless session data after this signup. Someone else might use this computer.
            $this->CI->session->unset_userdata("ref_by");
    		return "OK";
    	}else{
    		$out = "<div style='margin-top:10px; padding:10px; color:red; font-weight:bold;'>ERRORS FOUND:";
    		$out .= "<ol>";
    		foreach($err as $error){
    			$out .= "<li>".$error."</li>";
    		}
    		$out .= "</ol>";
    		$out .= "<input type='button' onClick=\"location.href='".$this->CI->config->item("base_url")."auth/signup';\" value='<< Go Back' style='border:auto; cursor:pointer; background:red; font-weight:bold; color:white;' />";
    		$out .= "</div>"; 
    		return $out;
    	}
    }
    
}
?>